package com.emotion.recognition.server.mlp;

import java.util.List;

import com.google.common.collect.Lists;

/**
 * Abstract node that remembers the last output value (for convenience), and manages outgoing edges.
 * Incoming edges are optional, so they should be managed in subclasses.
 * 
 * @author Minsang
 */
public abstract class AbstractNode implements Node {

    private final List<Edge> outgoingEdges = Lists.newArrayList();

    /**
     * The last output value of this node, useful only for UI / debugging.
     */
    private double lastOutput;

    private String name;

    /**
     * Add an outgoing edge. Do not call this method. Should be only called by
     * {@link Edge#connect(Perceptron, Perceptron)}.
     */
    @Override
    public final void addOutgoingEdge(Edge outgoing) {
        assert outgoing.getSource() == this;
        outgoingEdges.add(outgoing);
    }

    protected final void fire(double output) {
        // Remember the last output for debugging purposes
        lastOutput = output;

        // Propagate to next layer
        for (Edge e : outgoingEdges) {
            e.propagate(output);
        }
    }

    @Override
    public final double getLastOutput() {
        return lastOutput;
    }

    @Override
    public String getName() {
        return name;
    }

    @Override
    public List<Edge> getOutgoingEdges() {
        return outgoingEdges;
    }

    @Override
    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return name;
    }
}
